package com.evolve.autotest.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class Configurations extends Properties {

	private final static Logger logger = Logger.getLogger(Configurations.class);

	/**
	 * Serial ID
	 */
	private static final long serialVersionUID = 1L;

	private static Configurations instance;

	private static Object lock = new Object();

	/**
	 * Gets the only instance of this object.
	 * 
	 * @return
	 */
	public static Configurations getInstance() {
		synchronized (lock) {
			if (instance == null) {
				instance = new Configurations();
			}

			return instance;
		}
	}

	/**
	 * Returns a value as a key
	 * 
	 * @param key
	 * @return
	 */
	public int getIntProperty(final String key) {
		try {
			return Integer.parseInt(instance.getProperty(key));
		} catch (NumberFormatException e) {
			logger.error("Unable to convert the value to a integer. Key " + key + " value " + instance.getProperty(key));
			return -1;
		}
	}

	/**
	 * This will return the given property.
	 */
	public String getProperty(final String key) {
		if (key == null) {
			logger.error("Unable to find the property. Key " + key);
			return null;
		}

		return super.getProperty(key);
	}

	/**
	 * This will return the given property. If the property is null, the def
	 * value will be used
	 */
	public String getProperty(final String key, final String def) {
		final String value = super.getProperty(key);

		if (value == null) {
			return def;
		}

		return value;
	}

	/**
	 * This will initialize the configuration.
	 * 
	 * @param configFile
	 *            The file with the configurations.
	 * @return
	 */
	public boolean loadFromFile(final String configFile) {

		if (configFile == null || configFile.equalsIgnoreCase("")) {
			logger.error("The configuration file was null or empty " + configFile);
			return false;
		}

		try {
			FileInputStream inStream = new FileInputStream(configFile);
			this.load(inStream);
			inStream.close();
		} catch (FileNotFoundException e) {
			logger.error("The file " + configFile + " did not exist");
			return false;
		} catch (IOException e) {
			logger.error("A IO Exception ocurred \n" + e);
			return false;
		}

		return true;
	}
}
